package com.itheima.shop.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itheima.shop.dto.UserMessage;
import com.itheima.shop.entity.User;
import com.itheima.shop.service.UserService;
import com.itheima.shop.util.CookieUtil;

@Controller
@RequestMapping("/user")
public class UserController {

	private final static Logger logger = LoggerFactory.getLogger(UserController.class);

	@Autowired
	private UserService userService;

	@Autowired
	private HttpServletRequest request;

	@Autowired
	private HttpServletResponse response;

	@RequestMapping(value = "/login")
	public String login(String username, String password, @RequestParam(defaultValue = "false") Boolean remember,
			@RequestParam(defaultValue = "false") Boolean auto) {
		UserMessage userMsg = userService.Login(username, password);
		logger.info("/login success: user:" + userMsg + ",remember:" + remember);
		if (userMsg.getMsgCode() == 1001) {
			HttpSession session = request.getSession(true);
			session.setAttribute("user", userMsg);

			// 如果设置自动登录，则往客户端写一个cookie
			if (remember == true) {
				CookieUtil.addCookie(request, response, "username", username, 7 * 60 * 60 * 24);
				CookieUtil.addCookie(request, response, "remember", remember.toString(), 7 * 60 * 60 * 24);
			} else {
				CookieUtil.delCookie(request, response, "username");
				CookieUtil.delCookie(request, response, "remember");
			}

			// 保持登录记住状态
			/*
			 * 1. `UserController`获取前端勾选的`自动登录checkbox`值参数`auto` 
			 * 2. 执行正常的登录逻辑，根据账号查询数据库，比对账号密码，成功则设置session记录账号 
			 * 3. `UserController`判断auto是否勾选 ​
			 * 3.1 如果已勾选则需要设置session的超时时间，且在response添加2个cookie
			 * 一个`Key`为`AUTO`用于记录客户端自动登录勾选框，便于下次启动自动勾选`自动登录checkbox` ​
			 * 一个`Key`为`JSESSIONID`，用于重设置默认`JSESSIONID`的时间，使其不再随着浏览器关闭而销毁 ​ 
			 * 3.2  如果未勾选则清除掉key为`AUTO`的cookie，使下次不再自动勾选`自动登录checkbox`
			 * 
			 * 4. 前端`登录页login.jsp`获取`key`为`AUTO`的`cookie的值value`设置`自动登录checkbox`
			 */
			if (auto == true) {
				//设置session的超时时间
				session.setMaxInactiveInterval( 7 *60 * 60 * 24);
				// 通过cookie记录勾选框
				CookieUtil.addCookie(request, response, "auto", auto.toString(),  7 *60 * 60 * 24);
				//修改JSESSIONId
				CookieUtil.editCookie(request, response, "JSESSIONID", session.getId(),  7 *60 * 60 * 24);
			} else {
				CookieUtil.delCookie(request, response, "auto");
			}
			

		}
		request.setAttribute("MSG_CODE", userMsg.getMsgCode());
		return "message";
	}

	@RequestMapping(value = "/logout")
	public String logout(String username) {
		HttpSession session = request.getSession();
		session.invalidate();
		return "redirect:/index.jsp";
	}

	@RequestMapping(value = "/checkUserName")
	@ResponseBody
	public User validateUser(String username) {
		logger.info("mapping=/validateUser,parameters=username:" + username);
		User user = userService.checkUsername(username);
		logger.info(user.toString());
		return user;
	}

	@RequestMapping(value = "/regist")
	public String insert(User user) {
		UserMessage userMsg = userService.register(user);
		logger.info("/regist,user:" + user + ",userMsg:" + userMsg);
		request.setAttribute("MSG_CODE", userMsg.getMsgCode());
		return "message";
	}

	@RequestMapping(value = "/activate")
	public String activate(String code) {
		UserMessage userMsg = userService.activate(code);
		logger.info("/activate,code:" + code + ",result:" + userMsg.getMsgCode());
		request.setAttribute("MSG_CODE", userMsg.getMsgCode());
		return "message";
	}
}
